<template>
  <el-card>
    <template #header>
      <el-row :gutter="30">
        <el-col :span="22">
          <div class="mt-4">
            <el-input
              v-model="queryInfo.query"
              placeholder="请输入搜索内容"
              class="input-with-select"
              clearable
            >
              <template #prepend>
                <el-button :icon="Search" />
              </template>
            </el-input>
          </div>
        </el-col>
        <el-col :span="2">
          <el-button type="success" @click="getUserList">搜索</el-button>
        </el-col>
      </el-row>
    </template>

    <!-- 用户列表表格 -->
    <div class="table-container" style="width: 100%">
      <el-table :data="userList" border style="width: 100%" v-loading="loading">
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="username" label="用户名" width="180" />
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="password" label="密码" width="200">
          <template #default="{ row }">
            <!-- 密码显示为星号 -->
            {{ "*".repeat(row.password ? row.password.length : 0) }}
          </template>
        </el-table-column>
        <el-table-column prop="role" label="角色" width="200">
          <!-- 插槽获取数据，标签显示数据 -->
          <template #default="{ row }">
            <el-tag :type="getRoleTagType(row.role)">
              {{ formatRole(row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态" width="180">
          <!-- 开关标签 -->
          <template #default="{ row }">
            <el-switch
              v-model="row.state"
              :active-value="true"
              :inactive-value="false"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">修改</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryInfo.pageNum"
        v-model:page-size="queryInfo.pageSize"
        :page-sizes="[5, 10, 20, 50]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="getUserList"
        @current-change="getUserList"
      />
    </div>
    <!-- 编辑用户对话框 -->
<el-dialog v-model="editDialogVisible" title="修改用户信息" width="30%">
  <el-form :model="editForm" label-width="80px">
    <el-form-item label="邮箱">
      <el-input v-model="editForm.email" />
    </el-form-item>
    <el-form-item label="角色">
      <el-select v-model="editForm.role" placeholder="请选择角色">
        <el-option label="管理员" value="admin" />
        <el-option label="编辑" value="editor" />
        <el-option label="普通用户" value="user" />
      </el-select>
    </el-form-item>
  </el-form>
  <template #footer>
    <span class="dialog-footer">
      <el-button @click="editDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitEdit">确认</el-button>
    </span>
  </template>
</el-dialog>
  </el-card>
  
</template>

<script setup>
import { Search } from "@element-plus/icons-vue";
import { ref, onMounted } from "vue";
import api from "../../services/api";
import { ElMessage } from "element-plus";

// 初始化 queryInfo
const queryInfo = ref({
  query: "",
  pageNum: 1,
  pageSize: 5,
});

// 用户列表数据
const userList = ref([]);
const total = ref(0);
const loading = ref(false);

// 获取用户列表
const getUserList = async () => {
  try {
    loading.value = true;
    const res = await api.getalluser(queryInfo.value);

    userList.value = res.data.users;
    //获取总用户数量
    total.value = res.data.numbers || res.data.users.length;
  } catch (error) {
    console.error("获取用户列表失败:", error);
    ElMessage.error("获取用户列表失败");
  } finally {
    loading.value = false;
  }
};

// 处理状态变更
const handleStatusChange = async (row) => {
  console.log(row.state);
  try {
    const req = await api.upDatestate({
      id: row.id,
      state: row.state,
    });
    console.log(req);
    if (req.data !== "success") {
      throw new Error("修改失败");
    }
    ElMessage.success("状态更新成功");
  } catch (error) {
    // 出错时恢复原来的状态

    ElMessage.error("修改失败: " + (error.message || error));
  }
};
// 编辑对话框相关
const editDialogVisible = ref(false);
const editForm = ref({
  id: '',
  email: '',
  role: ''
});

// 打开编辑对话框
const handleEdit = (row) => {
  editForm.value = {
    id: row.id,
    email: row.email,
    role: row.role
  };
  editDialogVisible.value = true;
};

// 提交修改
const submitEdit = async () => {
  try {
    const res = await api.updateUser(editForm.value);
    if (res.data === "success") {
      ElMessage.success('修改成功');
      editDialogVisible.value = false;
      getUserList(); // 刷新列表
    } else {
      throw new Error('修改失败');
    }
  } catch (error) {
    ElMessage.error('修改失败: ' + (error.message || error));
  }
};
// 格式化角色显示
const formatRole = (role) => {
  const roleMap = {
    admin: "管理员",
    editor: "编辑",
    user: "普通用户",
  };
  return roleMap[role] || role;
};

// 获取角色标签类型
const getRoleTagType = (role) => {
  const typeMap = {
    admin: "danger",
    editor: "warning",
    user: "success",
  };
  return typeMap[role] || "";
};

// 在组件挂载后执行初始化
onMounted(() => {
  getUserList();
});
</script>
 
<style scoped>
.el-row {
  width: 100%;
}
.el-col {
  width: 100%;
}

/* 让表格铺满整个 card */
.table-container {
  padding: 0 10px; /* 可选：添加一些内边距 */
}

/* 分页容器样式 */
.pagination-container {
  margin-top: 20px; /* 增加分页与表格的间距 */
  display: flex;
  justify-content: center; /* 分页靠右对齐 */
}
</style>